#!/usr/bin/python
# coding:utf-8

import asyncore
import smtpd
import smtplib


class SMTPChannel(smtpd.SMTPChannel):

    # SMTP and ESMTP commands
    def smtp_EHLO(self, arg):
        if not arg:
            self.push('501 Syntax: HELO hostname')
            return
        if self.__greeting:
            self.push('503 Duplicate HELO/EHLO')
        else:
            self.__greeting = arg
            self.push('250 %s' % self.__fqdn)


class SMTPServer(smtpd.SMTPServer):

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            conn, addr = pair
            print >> smtpd.DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
            channel = SMTPChannel(self, conn, addr)

    def process_message(self, peer, mailfrom, rcpttos, data):
        # print mailfrom, rcpttos
        server = smtplib.SMTP("127.0.0.1", 25)
        # server.set_debuglevel(1)
        server.sendmail(mailfrom, rcpttos, data)
        server.close()


SMTPServer(('0.0.0.0', 465), None)
asyncore.loop()
